package com.game.connection.client;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import com.game.connection.message.BulletMessage;
import com.game.connection.message.Message;
import com.game.entity.Bullet;
import com.game.entity.Ship;
import com.game.listener.ShipListener;
import com.game.listener.event.ShipEvent;

public class ClientPlayerSender implements Runnable, ShipListener {
	private PrintWriter out;
	private Integer playerId;
	private Ship ship;
	private ShipEvent event = null;
	private HashMap<Integer, Ship > ships;

	public ClientPlayerSender(Integer id, OutputStream outPutStream, Ship ship,
			HashMap<Integer, Ship > ships) {
		playerId = id;
		this.ships = ships;
		this.out = new PrintWriter(outPutStream, true);
		this.ship = ship;
		ship.setId(playerId);
	}

	public void send() {
		// System.out.println(playerId);
		Message msg = new Message();

		
		msg.setId(playerId);
		msg.setX(ship.getX());
		msg.setY(ship.getY());
		msg.setVelX(ship.getVelX());
		msg.setVelY(ship.getVelY());
		msg.setFaceAngle(ship.getFaceAngel());
		
		if (ship.getMessage().size() > 0) {
			msg.setMessage(ship.getMessage().remove(
					ship.getMessage().size() - 1));
		}
		for (Bullet bullet : ship.getBullets()) {
			BulletMessage bulletMsg = new BulletMessage();
			bulletMsg.setFaceAngle(bullet.getFaceAngel());
			bulletMsg.setX(bullet.getX());
			bulletMsg.setY(bullet.getY());
			bulletMsg.setVelY(bullet.getVelY());
			bulletMsg.setVelX(bullet.getVelX());
			bulletMsg.setAlive(bullet.isAlive());
			msg.getBullets().add(bulletMsg);
		}

		out.println(msg.write());
	}

	@Override
	public void run() {
		while (true) {

			try {
				synchronized (this.ship) {
					this.ship.wait();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			send();
		}
	}

	@Override
	public void moveAction(ShipEvent event) {
		// System.err.println(Thread.currentThread().getName() +
		// " mudanca de posicoes..." + event);

		this.event = event;

		synchronized (this.ship) {
			this.ship.notifyAll();
		}
	}
}
